package redis

import (
	"cart_srv/cart"
	"context"
	"fmt"
	"sort"
	"strconv"
)

func CartAdd(cart map[string]interface{}) error {
	Key := fmt.Sprintf("cart:%d:%d", cart["user_id"], cart["good_id"])
	return Rdb.HMSet(context.Background(), Key, cart).Err()
}

func CartExist(userId, goodId int64) bool {
	Key := fmt.Sprintf("cart:%d:%d", userId, goodId)
	return Rdb.Exists(context.Background(), Key).Val() == 1
}

func UpdateNumCart(userId, goodId, num int64) error {
	Key := fmt.Sprintf("cart:%d:%d", userId, goodId)
	return Rdb.HIncrBy(context.Background(), Key, "num", num).Err()
}

func CartList(userId int64) (cartList []*cart.ListItem, err error) {
	Key := fmt.Sprintf("cart:%d:*", userId)
	keys := Rdb.Keys(context.Background(), Key).Val()
	for _, key := range keys {
		goodMap := Rdb.HGetAll(context.Background(), key).Val()
		UserId, _ := strconv.Atoi(goodMap["user_id"])
		goodId, _ := strconv.Atoi(goodMap["good_id"])
		num, _ := strconv.Atoi(goodMap["num"])
		goodPrice, _ := strconv.ParseFloat(goodMap["good_price"], 64)
		cartList = append(cartList, &cart.ListItem{
			UserId:    int64(UserId),
			GoodId:    int64(goodId),
			Num:       int64(num),
			GoodTitle: goodMap["good_title"],
			GoodPrice: float32(goodPrice),
		})
		sort.Slice(cartList, func(i, j int) bool {
			return cartList[i].GoodPrice > cartList[j].GoodPrice
		})
	}
	return
}
